import React from 'react';
import type { SettingApproverType, DataType, TreeType } from './data.d';
import {
  Tag,
  Form,
  Button,
  Select,
  Modal,
  Radio,
  Col,
  Row,
  Table,
  Input,
  message,
} from 'antd';
import { columns } from './data';
import TagRender from './TagRender';
import SearchTree from '../../../../components/SearchTree';
import type { RadioChangeEvent } from 'antd';
import { getOrgTree, getUser } from '../../../../services/upmsServices';

const { Option } = Select;

const SettingApprover = (props: SettingApproverType) => {
  const { currentElement, modeler } = props;
  // 审批人表单
  const [SettingApproverForm] = Form.useForm();
  // 控制审批人模态框
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  // 审批人list
  const [approvers, setApprovers] = React.useState<DataType[]>([]);
  // 审批人key
  const [approversKey, setApproversKey] = React.useState<React.Key[]>([]);
  // 审批人类型
  const [approversType, setApproversType] = React.useState<string>('1');
  // 变量类型
  const [variableType, setVariableType] = React.useState<string>('1');
  // 树数据
  const [orgTree, setOrgTree] = React.useState<TreeType>([]);
  // 表格数据
  const [tableData, setTableData] = React.useState([]);
  // 审批人类型
  const [approverType, setApproverType] = React.useState<string>('1');
  // 组织id
  const [orgId, setOrgId] = React.useState<string>();
  // 会签类型
  const [countersignType, setCountersignType] = React.useState<string>('1');

  React.useEffect(() => {
    let obj = currentElement.businessObject?.$attrs;
    // loopCharacteristics 存在为会签状态
    if (currentElement.businessObject?.loopCharacteristics) {
      const { collection, elementVariable, isSequential, completionCondition } =
        currentElement.businessObject?.loopCharacteristics;
      setCountersignType(isSequential ? '3' : '2');
      setApproverType('4');
      SettingApproverForm.setFieldsValue({
        countersignType: isSequential ? '3' : '2',
        collection,
        elementVariable,
        condition: completionCondition.body,
        approver: [obj['flowable:assignee']],
        type: '4',
      });
    } else {
      SettingApproverForm.setFieldValue('countersignType', '1');
      if (
        obj['flowable:assignee'] &&
        obj['flowable:assignee'] == '$INITIATOR'
      ) {
        setApproverType('1');
        SettingApproverForm.setFieldValue('type', '1');
      } else if (obj['flowable:assignee'] && obj['custom:userinfo']) {
        setApproverType('2');
        let { userId, approversType, orgId, username } = JSON.parse(
          obj['custom:userinfo'],
        );
        SettingApproverForm.setFieldsValue({
          type: '2',
          approver: [username],
        });
        setApproversKey([userId]);
        setApproversType(approversType);
        setOrgId(orgId);
        getTableData(orgId);
        setApprovers([
          {
            username: username,
            userId: userId,
            orgId: orgId,
          },
        ]);
      } else if (obj['flowable:assignee'] && !obj['custom:userinfo']) {
        setApproverType('4');
        SettingApproverForm.setFieldsValue({
          type: '4',
          approver: obj['flowable:assignee'],
        });
      } else if (obj['flowable:candidateUsers']) {
        setApproverType('3');
        let userinfo = JSON.parse(obj['custom:userinfo']);
        setApproversType(userinfo.approversType);
        let approver: string[] = [];
        let orgId: string = '';
        let approverList = userinfo.approvers.map(
          (item: any, index: number) => {
            approver.push(item.username);
            if (index == 0) {
              orgId = item.orgId;
            }
            return {
              username: item.username,
              userId: item.userId,
              orgId: item.orgId,
            };
          },
        );
        SettingApproverForm.setFieldsValue({
          type: '3',
          approver,
        });
        setOrgId(orgId);
        setApproversKey(obj['flowable:candidateUsers'].split(','));
        getTableData(orgId);
        setApprovers(approverList);
      }
    }
  }, []);
  // 会签类型改变
  const countersignTypeChange = (e: string) => {
    setCountersignType(e);
    if (e !== '1') {
      SettingApproverForm.setFieldsValue({ type: '4', approver: '' });
      setApproverType('4');
    }
  };

  // 改变审批类型
  const typeChange = (e: string) => {
    setApprovers([]);
    setApproversKey([]);
    SettingApproverForm.setFieldValue('approver', []);
    setApproverType(e);
  };

  // 打开选择审批人弹框
  const showApproverModal = () => {
    setIsModalOpen(true);
    getOrgList();
  };

  // 选择审批人类型
  const onRadioChange = (e: RadioChangeEvent) => {
    setApproversType(e.target.value);
  };

  // 获取机构树
  const getOrgList = async () => {
    let res = await getOrgTree({});
    if (res.code !== '000000') {
      message.error('获取机构信息失败');
      return;
    }
    setOrgTree(setTree(res.data));
  };

  // 打造机构树
  const setTree = (arr: any) => {
    let tree = arr.map((item: any) => {
      let obj = {
        title: item.orgName,
        key: item.orgId,
        children: [],
      };
      if (item.children.length !== 0) {
        obj.children = setTree(item.children);
      }
      return obj;
    });
    return tree;
  };

  // 获取表格数据
  const getTableData = async (orgId: string) => {
    setOrgId(orgId);
    let res = await getUser({ orgId });
    if (res.code !== '000000') {
      message.error('获取审批人表格失败');
      return;
    }
    setTableData(res.data);
  };

  // 变量输入形式
  const onVariableChange = (e: RadioChangeEvent) => {
    setVariableType(e.target.value);
  };

  // 表格勾选函数
  const onSelectChange = (
    selectedRowKeys: React.Key[],
    selectedRows: DataType[],
  ) => {
    setApprovers(selectedRows);
    setApproversKey(selectedRowKeys);
  };

  // 表格设置
  const rowSelection = {
    selectedRowKeys: approversKey,
    onChange: onSelectChange,
  };

  // 标签取消
  const onTagClose = (item: DataType) => {
    let arr = approvers.filter((i: DataType) => {
      return i != item;
    });
    let arr1 = approversKey.filter((i: React.Key) => {
      return i != item.userId;
    });
    setApproversKey(arr1);
    setApprovers(arr);
  };

  // 审批人选择弹框确定
  const handleModalOk = () => {
    let arr = approvers.map((item) => {
      // console.log(item);
      return item.username;
    });
    SettingApproverForm.setFieldValue('approver', arr);
    setIsModalOpen(false);
    addApprover();
  };

  // 审批人弹框取消
  const handleModalCancel = () => {
    setIsModalOpen(false);
  };

  // 添加审批人
  const addApprover = async () => {
    // 会签类型 1 无、 2 串行、 3 并行
    if (countersignType == '1') {
      /**
       * 1 指定发起人为审批人
       * 2 指定审批人
       * 3 指定候选人
       * 4 固定值
       */
      if (approverType == '1') {
        let properties: any = {};
        properties['flowable:assignee'] = '$INITIATOR';
        updateProperties(properties);
      } else if (approverType == '2') {
        let properties: any = {};
        let approver: any = approvers[0];
        approver.approversType = approversType;
        properties['flowable:assignee'] = approver.userId;
        properties['custom:userinfo'] = JSON.stringify(approver);
        console.log(properties);

        updateProperties(properties);
      } else if (approverType == '3') {
        let properties: any = {};
        let candidateUsers = approvers.map((item) => {
          return item.userId;
        });
        properties['flowable:candidateUsers'] = candidateUsers.toString();
        let userinfo = {
          approversType,
          approvers,
        };
        properties['flowable:assignee'] = '';
        properties['custom:userinfo'] = JSON.stringify(userinfo);
        updateProperties(properties);
      } else if (approverType == '4') {
        let approver = await SettingApproverForm.getFieldsValue();
        let properties: any = {};
        properties['flowable:assignee'] = approver.approver;
        properties['flowable:candidateUsers'] = '';
        properties['custom:userinfo'] = '';
        updateProperties(properties);
      }
    }
    if (countersignType == '2') {
      let approver = await SettingApproverForm.getFieldsValue();
      addCountersign(approver);
    }
    if (countersignType == '3') {
      let approver = await SettingApproverForm.getFieldsValue();
      addCountersign(approver);
    }
  };

  /**
   * 更新元素属性
   * @param { Object } 要更新的属性, 例如 { name: '', id: '' }
   */
  const updateProperties = (properties: any) => {
    delete currentElement.businessObject.loopCharacteristics;
    const modeling = modeler.get('modeling');
    modeling.updateProperties(currentElement, properties);
  };

  /**
   * 添加会签标签
   */
  const addCountersign = (approver: any) => {
    let properties: any = {};
    properties['flowable:assignee'] = approver.approver;
    properties['flowable:candidateUsers'] = '';
    properties['custom:userinfo'] = '';
    updateProperties(properties);
    let loopCharacteristics = currentElement.businessObject.get(
      'loopCharacteristics',
    );
    if (!loopCharacteristics) {
      loopCharacteristics = modeler
        .get('moddle')
        .create('bpmn:MultiInstanceLoopCharacteristics');
    }
    loopCharacteristics.isSequential =
      approver.countersignType == '3' ? true : false;
    loopCharacteristics.$attrs['flowable:collection'] = approver.collection;
    loopCharacteristics.$attrs['flowable:elementVariable'] =
      approver.elementVariable;
    let completionCondition = modeler.get('moddle').create('bpmn:Expression');
    completionCondition.body = approver.condition;
    loopCharacteristics.completionCondition = completionCondition;
    currentElement.businessObject.loopCharacteristics = loopCharacteristics;
  };

  return (
    <>
      <Form form={SettingApproverForm}>
        <Form.Item label="会签" name="countersignType">
          <Select placeholder="请选择会签类型" onChange={countersignTypeChange}>
            <Option value="1">无</Option>
            <Option value="2">串行</Option>
            <Option value="3">并行</Option>
          </Select>
        </Form.Item>
        <Form.Item label="审批人类型" name="type">
          <Select placeholder="请选择审批人类型" onChange={typeChange}>
            <Option value="1" disabled={countersignType !== '1'}>
              指定发布者为审批人
            </Option>
            <Option value="2" disabled={countersignType !== '1'}>
              指定审批人
            </Option>
            <Option value="3" disabled={countersignType !== '1'}>
              指定候选人
            </Option>
            <Option value="4">固定值</Option>
          </Select>
        </Form.Item>
        {approverType !== '4' ? (
          <Form.Item label="审批人">
            <Row>
              <Col span={12}>
                <Form.Item name="approver">
                  <Select
                    mode="multiple"
                    showArrow
                    disabled
                    tagRender={TagRender}
                    style={{ width: '100%' }}
                    placeholder="请配置审批人"
                    suffixIcon=""
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Button
                  type="primary"
                  disabled={approverType == '1' || approverType == '4'}
                  onClick={showApproverModal}
                >
                  添加人选
                </Button>
              </Col>
            </Row>
          </Form.Item>
        ) : (
          <>
            <Form.Item label="审批人" name="approver">
              <Input />
            </Form.Item>
            {countersignType !== '1' ? (
              <>
                <Form.Item label="集合名" name="collection">
                  <Input />
                </Form.Item>
                <Form.Item label="元素名" name="elementVariable">
                  <Input />
                </Form.Item>
                <Form.Item label="通过条件" name="condition">
                  <Input />
                </Form.Item>
              </>
            ) : null}
          </>
        )}
      </Form>
      <Modal
        width={1000}
        title="选择审批人"
        open={isModalOpen}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        okText="确定"
        cancelText="取消"
      >
        <Radio.Group onChange={onRadioChange} value={approversType}>
          <Radio value={'1'}>用户</Radio>
          <Radio value={'2'}>机构</Radio>
          <Radio value={'3'}>岗位</Radio>
          <Radio value={'4'}>角色</Radio>
          <Radio value={'5'}>变量</Radio>
        </Radio.Group>
        {approversType !== '5' ? (
          <Row gutter={16} style={{ marginTop: 10 }}>
            <Col span={6}>
              <SearchTree
                // 渲染数据
                checkedId={orgId}
                treeData={orgTree}
                changeKey={getTableData}
              />
            </Col>
            <Col span={12}>
              <Table
                rowSelection={{
                  type: approverType === '2' ? 'radio' : 'checkbox',
                  ...rowSelection,
                }}
                columns={columns}
                dataSource={tableData}
                rowKey="userId"
              />
            </Col>
            <Col span={6}>
              {approvers.map((item) => {
                return (
                  <Tag
                    closable
                    key={item.userId}
                    color="blue"
                    onClose={() => onTagClose(item)}
                  >
                    {item.username}
                  </Tag>
                );
              })}
            </Col>
          </Row>
        ) : (
          <Form form={SettingApproverForm} style={{ marginTop: 10 }}>
            <Form.Item label="请选择：" name="type">
              <Radio.Group onChange={onVariableChange} value={variableType}>
                <Radio value={1}>手动输入</Radio>
                <Radio value={2}>自动生成</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="请输入" name="approver">
              <Input placeholder="请输入" disabled={variableType !== '1'} />
            </Form.Item>
          </Form>
        )}
      </Modal>
    </>
  );
};

export default SettingApprover;
